﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ComputerResourceConsole.lib;
using ComputerResourceConsole.factory;
using ComputerResourceConsole.common;
using ComputerResourceConsole.control;
using System.Diagnostics;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using ComputerResourceConsole.bean;

namespace ComputerResourceConsole.view
{
    public partial class frm_version : Form
    {

        private IConfig _pConfig = null;
        public static bool flag = true;
        private frm_update _frm_update = null;

        public frm_version()
        {
            InitializeComponent();
            try
            {
                this._pConfig = ComponentOperaFactory.createConfig();
                this._pConfig.loadConfig();
                String origin_version = getContainerVersion();
                origin_version = origin_version.Replace(System.Environment.NewLine, String.Empty);
                origin_version = origin_version.Replace("\n", String.Empty);
                //组件显示
                this.setVersionView(origin_version, Color.Green);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        //获取当前文件夹下模型容器的版本号
        private String getContainerVersion()
        {
            String output_result = "";
            String cmd = " --version";
            String path_exe = this._pConfig.NodejsPath;
            String test_Path = CommonMethod.getAppDirection() + path_exe;
            Console.WriteLine(test_Path);
            if (!File.Exists(test_Path))
            {
                //文件不存在表明没有模型服务容器exe，为了使后面不报错，返回版本号为0.0.1
                MessageBox.Show("Can not find the current model container application", "System Attention", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "0.0.1";
            }
            try
            {
                Process process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.FileName = CommonMethod.getAppDirection() + path_exe;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.Arguments = cmd;

                //执行
                process.Start();

                output_result = process.StandardOutput.ReadToEnd();

                process.WaitForExit();

                process.Close();

            }
            catch (System.Exception ex)
            {
                Console.Write(ex);
            }
            return output_result;
        }

        //设置Version View的界面
        private void setVersionView(String content, Color txtColor)
        {
            this.loadingBox.Visible = false;
            this.current_version.Text = content;
            this.current_version.ForeColor = txtColor;
            this.latest_version.ForeColor = Color.Red;
        }

        private void check_button_Click(object sender, EventArgs e)
        {
            //先改变状态
            this.loadingBox.Visible = true;
            this.latest_version.Text = "";
            this.check_button.Enabled = false;

            //刷新控件状态
            System.Windows.Forms.Application.DoEvents();

            //发起网络请求
            string url = this._pConfig.VersionCheckPath;
            try{

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resoponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(resoponseStream, Encoding.UTF8);
                string resString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                resoponseStream.Close();

                //字符串格式化一下

                //解析json
                RootObject result = JsonConvert.DeserializeObject<RootObject>(resString);
                if (result.msg.Equals("suc"))
                {
                    string version_information = result.data.version;
                    Version current = new Version(this.current_version.Text);
                    Version latest = new Version(version_information);
                    if (current >= latest)
                    {
                        MessageBox.Show("The Current model container has been the latest version", "System Attention", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.loadingBox.Visible = false;
                        this.latest_version.Text = version_information;
                        this.latest_version.ForeColor = Color.Green;
                        this.check_button.Enabled = true;
                    }
                    else
                    {
                        //首先更改状态
                        this.loadingBox.Visible = false;
                        this.latest_version.Text = version_information;
                        this.latest_version.ForeColor = Color.Green;
                        this.check_button.Enabled = true;

                        //跳转页面
                        this._frm_update = new frm_update();
                        this._frm_update.Show();

                        //this.Close();
                    }
                }
                else
                {
                    //说明未能成功获取
                    MessageBox.Show("Unable to get the latest version information, Please check the internet and try again!", "System Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.loadingBox.Visible = false;
                    this.latest_version.Text = "Unknown";
                    this.latest_version.ForeColor = Color.Red;
                    this.check_button.Enabled = true;
                }


            }catch(Exception ex){
                //error handler, TO DO!
                MessageBox.Show(ex.Message, "System Attention", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.loadingBox.Visible = false;
                this.latest_version.Text = "Unknown";
                this.latest_version.ForeColor = Color.Red;
                this.check_button.Enabled = true;
            }
            
        }


    }
}
